<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-icon><VideoCamera /></el-icon>
        <span style="margin-left: 8px;">在线直播 - {{ roomName }}</span>
        <el-tag :type="isConnected ? 'success' : 'danger'" style="margin-left: 20px;">
          {{ isConnected ? '已连接' : '未连接' }}
        </el-tag>
        <el-tag v-if="isRecording" type="warning" effect="dark" style="margin-left: 10px;">
           <el-icon class="is-loading"><Loading /></el-icon>
           <span style="margin-left: 4px">录制中...</span>
        </el-tag>
      </div>
    </template>
    
    <div class="main-content-wrapper">
        <div class="live-layout">
            <div 
                v-loading="isLoading" 
                element-loading-text="正在进入直播间..." 
                class="video-container"
                :class="layoutMode"
                ref="videoContainerRef"
            >
                <div v-if="currentPoll && userRole === 'subscriber'" class="poll-overlay">
                    <el-card class="poll-card">
                        <h4>【{{ currentPoll.dialogType === 'quiz' ? '随堂测验' : '问卷投票' }}】</h4>
                        <p class="poll-question">{{ currentPoll.question }}</p>
                        <div class="poll-options">
                            <el-button 
                                v-for="(option, index) in currentPoll.options" 
                                :key="index"
                                @click="submitPollAnswer(index)"
                                :disabled="pollSubmitted"
                            >
                                {{ option }}
                            </el-button>
                        </div>
                        <p v-if="pollSubmitted" class="poll-feedback">已提交您的答案！</p>
                    </el-card>
                </div>

                <div v-if="currentPoll && userRole === 'publisher'" class="poll-results-overlay">
                    <el-card class="poll-card">
                        <h4>【{{ currentPoll.dialogType === 'quiz' ? '测验结果' : '投票结果' }}】({{ totalVotes }}人已参与)</h4>
                        <p class="poll-question">{{ currentPoll.question }}</p>
                        <div v-for="(option, index) in currentPoll.options" :key="index" class="poll-result-item">
                            <span>{{ option }}</span>
                            <el-progress :percentage="getVotePercentage(index)" :stroke-width="20" :text-inside="true" />
                        </div>
                        <el-button type="danger" size="small" @click="endPoll" style="margin-top: 10px;">结束{{ currentPoll.dialogType === 'quiz' ? '测验' : '投票' }}</el-button>
                    </el-card>
                </div>
            </div>

            <div class="sidebar-panel">
                <el-card class="chat-card">
                    <template #header>
                        <div class="chat-header">
                            <span>课堂互动</span>
                        </div>
                    </template>
                    <div class="chat-messages" ref="chatMessagesRef">
                        <div v-for="(msg, index) in chatMessages" :key="index" class="chat-message">
                            <span class="chat-user" :style="{ color: msg.color }">{{ msg.user }}:</span>
                            <span class="chat-content">{{ msg.content }}</span>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>

        <transition name="el-zoom-in-top">
            <div v-if="showFinalResults" class="final-results-panel">
                <el-card>
                    <template #header>
                        <div class="final-results-header">
                            <span>{{ finalResultsData?.dialogType === 'quiz' ? '最终测验结果' : '最终投票结果' }}</span>
                            <el-button type="info" link @click="showFinalResults = false">
                                <el-icon><CloseBold /></el-icon>
                            </el-button>
                        </div>
                    </template>
                    <div class="chart-container">
                        <v-chart class="chart" :option="chartOption" autoresize />
                    </div>
                </el-card>
            </div>
        </transition>
    </div>

    <template #footer>
      <div class="footer-controls">
        <div class="control-group-left">
          <template v-if="userRole === 'publisher'">
            <el-button @click="openDialog('quiz')" :disabled="!isConnected" type="primary" plain>
              <el-icon><EditPen /></el-icon><span class="btn-text">发起测验</span>
            </el-button>
            <el-button @click="openDialog('poll')" :disabled="!isConnected" type="warning" plain>
              <el-icon><DataAnalysis /></el-icon><span class="btn-text">发起投票</span>
            </el-button>
            <el-button @click="toggleScreenShare" :disabled="!isConnected" type="success" plain>
              <el-icon><Monitor /></el-icon><span class="btn-text">{{ isSharingScreen ? '停止共享' : '共享屏幕' }}</span>
            </el-button>
            <el-button @click="toggleSimulation" :disabled="!isConnected" :type="isSimulating ? 'danger' : 'success'" plain>
              <el-icon><Cpu /></el-icon><span class="btn-text">{{ isSimulating ? '结束模拟' : '开启虚拟学生' }}</span>
            </el-button>
          </template>
        </div>

        <div class="control-group-center">
            <el-button @click="applyBlurBackground" :loading="sceneLoading" :disabled="!isConnected">
                <el-icon><MagicStick /></el-icon>
                <span>背景虚化</span>
            </el-button>
            <el-button @click="applyFixedBackground" :loading="sceneLoading" :disabled="!isConnected">
                <el-icon><Picture /></el-icon>
                <span>固定背景</span>
            </el-button>
            <el-button @click="clearBackground" :disabled="!isConnected || sceneLoading">
                <el-icon><Close /></el-icon>
                <span>清除背景</span>
            </el-button>
        </div>

        <div class="control-group-right">
           <template v-if="userRole === 'publisher'">
             <el-button 
                :type="isRecording ? 'default' : 'danger'" 
                @click="handleRecording" 
                :disabled="!isConnected || isRecordingLoading"
                :loading="isRecordingLoading"
                plain
              >
               <el-icon><VideoCamera /></el-icon><span class="btn-text">{{ isRecording ? '停止录制' : '开始录制' }}</span>
             </el-button>
           </template>
           <el-button type="danger" @click="disconnect">
              <el-icon><SwitchButton /></el-icon>
              <span class="btn-text">{{ userRole === 'publisher' ? '结束直播' : '离开直播间' }}</span>
           </el-button>
        </div>
      </div>
    </template>

    <el-dialog v-model="showPollDialog" :title="`创建新的${dialogType === 'quiz' ? '随堂测验' : '问卷投票'}`" width="500px" @close="resetPollForm">
      <el-form :model="pollForm">
        <el-form-item label="问题">
          <el-input v-model="pollForm.question" placeholder="请输入您的问题" />
        </el-form-item>
        <el-form-item v-for="(option, index) in pollForm.options" :key="index" :label="`选项 ${index + 1}`">
           <el-input v-model="pollForm.options[index]" placeholder="请输入选项内容">
             <template #append>
               <el-button @click="removePollOption(index)" :disabled="pollForm.options.length <= 2"><el-icon><Delete /></el-icon></el-button>
             </template>
           </el-input>
        </el-form-item>
      </el-form>
       <div style="text-align: center; margin-bottom: 20px;">
          <el-button @click="addPollOption" >添加选项</el-button>
       </div>
      <template #footer>
        <el-button @click="showPollDialog = false">取消</el-button>
        <el-button type="primary" @click="startPoll">立即发起</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, shallowRef, reactive, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Room, RoomEvent, Track, DataPacket_Kind, createLocalVideoTrack } from 'livekit-client';
import { VirtualBackground, BackgroundBlur } from '@livekit/track-processors';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
import livekitService from '../../services/livekitService';
import simulationService from '../../services/simulationService';
import speechRecognitionService from '../../services/speechRecognitionService';
import { useAuthStore } from '../../stores/authStore';
import { useRoute } from 'vue-router';
import {
    VideoCamera, Loading, EditPen, DataAnalysis, Monitor, SwitchButton, Delete,
    CloseBold, Cpu, MagicStick, Picture, Close
} from '@element-plus/icons-vue';
// 【核心修正】直接导入图片资源
import backgroundImage from '../../assets/350.jpg';

echarts.use([
  CanvasRenderer,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart
]);

const sceneLoading = ref(false);

async function applyProcessor(processor) {
  if (!room.value?.localParticipant) return;
  sceneLoading.value = true;
  try {
    const cameraTrackPublication = room.value.localParticipant.getTrackPublication(Track.Source.Camera);
    if (!cameraTrackPublication || !cameraTrackPublication.videoTrack) {
        ElMessage.warning('未找到摄像头轨道，请先开启摄像头。');
        return false;
    }
    await cameraTrackPublication.videoTrack.setProcessor(processor);
    return true;
  } catch (error) {
    let errorMessage = '应用背景效果失败。';
    if (error.message && error.message.includes('Simd not supported')) {
        errorMessage = '应用背景效果失败：您的浏览器或设备不支持必需的 SIMD 技术。';
    } else if (error.message) {
        errorMessage = `应用背景失败: ${error.message}`;
    }
    ElMessage.error(errorMessage);
    console.error(error);
    return false;
  } finally {
    sceneLoading.value = false;
  }
}

const applyBlurBackground = async () => {
    ElMessage.info('正在应用背景虚化...');
    const success = await applyProcessor(BackgroundBlur(25, { assetsPath: '/models' }));
    if (success) {
        ElMessage.success('背景虚化已应用！');
    }
};

const applyFixedBackground = async () => {
    ElMessage.info('正在应用虚拟背景...');
    try {
        const image = new Image();
        // 【核心修正】使用导入的图片
        image.src = backgroundImage;
        await new Promise((resolve, reject) => {
            image.onload = resolve;
            image.onerror = reject;
        });

        const processor = VirtualBackground(image, {
            assetsPath: '/models',
        });
        
        const success = await applyProcessor(processor);
        if (success) {
            ElMessage.success('虚拟背景已应用！');
        }
    } catch (e) {
        ElMessage.error('加载背景图片失败。');
        sceneLoading.value = false;
        console.error(e);
    }
};

const clearBackground = async () => {
    try {
        const cameraTrackPublication = room.value.localParticipant.getTrackPublication(Track.Source.Camera);
        if (cameraTrackPublication && cameraTrackPublication.videoTrack && cameraTrackPublication.videoTrack.getProcessor()) {
            await cameraTrackPublication.videoTrack.stopProcessor();
            ElMessage.success('背景效果已清除。');
        }
    } catch (error) {
        ElMessage.error('清除背景效果失败。');
        console.error(error);
    }
};

const authStore = useAuthStore();
const route = useRoute();
const isLoading = ref(true);
const isConnected = ref(false);
const room = shallowRef(null);
const roomName = ref('teacher-lounge');
const videoContainerRef = ref(null);
const livekitUrl = 'wss://teacher001-ybu3m4f5.livekit.cloud';
const userRole = ref(route.query.role || 'subscriber');
const isSharingScreen = ref(false); 
const videoTracks = ref([]);
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const isRecording = ref(false);
const isRecordingLoading = ref(false);
const egressId = ref(null);
const showPollDialog = ref(false);
const dialogType = ref('poll');
const pollForm = reactive({ question: '', options: ['', ''] });
const currentPoll = ref(null);
const pollResults = reactive({});
const pollSubmitted = ref(false);
const showFinalResults = ref(false);
const finalResultsData = ref(null);
const isSimulating = ref(false);
const chatMessages = ref([]);
const chatMessagesRef = ref(null);
const userColors = {};
const availableColors = ['#E67E22', '#3498DB', '#2ECC71', '#9B59B6', '#F1C40F'];

const getUserColor = (userName) => {
    if (!userColors[userName]) {
        userColors[userName] = availableColors[Object.keys(userColors).length % availableColors.length];
    }
    return userColors[userName];
};

const scrollToChatBottom = () => {
    nextTick(() => {
        if (chatMessagesRef.value) {
            chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
        }
    });
};

const handleTeacherSpeech = (transcript) => {
  if (!isSimulating.value || !transcript) return;
  console.log('识别到教师讲课内容:', transcript);
  simulationService.sendTeacherSpeech(roomName.value, transcript);
};

const toggleSimulation = async () => {
    if (isSimulating.value) {
        await simulationService.stopSimulation();
        speechRecognitionService.stop(); 
        isSimulating.value = false;
        ElMessage.info('虚拟学生模拟已停止。');
    } else {
        const lessonContext = prompt("请输入本堂课的主题（如：勾股定理）", "初中数学：勾股定理的证明与应用");
        if (lessonContext) {
            try {
                await simulationService.startSimulation(roomName.value, lessonContext);
                speechRecognitionService.start(handleTeacherSpeech); 
                isSimulating.value = true;
                ElMessage.success('虚拟学生已进入教室，模拟开始！');
                chatMessages.value.push({
                    user: '系统提示',
                    content: '小明、小红、小刚已进入教室。',
                    color: '#909399'
                });
            } catch (error) {
                ElMessage.error(error.message);
            }
        }
    }
};

const totalVotes = computed(() => Object.values(pollResults).reduce((sum, count) => sum + count, 0));

const getVotePercentage = (optionIndex) => {
  if (totalVotes.value === 0) return 0;
  const votes = pollResults[optionIndex] || 0;
  return Math.round((votes / totalVotes.value) * 100);
};

const resetPollForm = () => {
    pollForm.question = '';
    pollForm.options = ['', ''];
};

const openDialog = (type) => {
  dialogType.value = type;
  showPollDialog.value = true;
};

const addPollOption = () => {
  if (pollForm.options.length < 6) pollForm.options.push('');
  else ElMessage.warning('最多只能添加6个选项');
};

const removePollOption = (index) => {
  pollForm.options.splice(index, 1);
};

const startPoll = async () => {
  if (!pollForm.question.trim() || pollForm.options.some(o => !o.trim())) {
    ElMessage.warning('问题和所有选项都不能为空');
    return;
  }
  showFinalResults.value = false;
  const pollData = {
    type: 'poll_start',
    payload: {
      dialogType: dialogType.value,
      question: pollForm.question,
      options: pollForm.options,
    }
  };
  currentPoll.value = pollData.payload;
  Object.keys(pollResults).forEach(key => delete pollResults[key]);
  const data = textEncoder.encode(JSON.stringify(pollData));
  await room.value.localParticipant.publishData(data, DataPacket_Kind.RELIABLE);
  showPollDialog.value = false;
};

const endPoll = async () => {
    const finalOptions = currentPoll.value.options;
    const finalVotes = finalOptions.map((opt, index) => pollResults[index] || 0);
    const finalDataPayload = {
        dialogType: currentPoll.value.dialogType,
        question: currentPoll.value.question,
        options: finalOptions,
        votes: finalVotes,
    };
    const message = { type: 'poll_final_results', payload: finalDataPayload };
    const data = textEncoder.encode(JSON.stringify(message));
    await room.value.localParticipant.publishData(data, DataPacket_Kind.RELIABLE);
    
    finalResultsData.value = finalDataPayload;
    showFinalResults.value = true;
    currentPoll.value = null;
};

const submitPollAnswer = async (answerIndex) => {
  const answerData = { type: 'poll_answer', payload: { answer: answerIndex } };
  const data = textEncoder.encode(JSON.stringify(answerData));
  await room.value.localParticipant.publishData(data, DataPacket_Kind.RELIABLE);
  pollSubmitted.value = true;
};

const handleDataReceived = (payload, participant) => {
  const data = JSON.parse(textDecoder.decode(payload));
  
  if (participant?.identity === authStore.user?.username && (data.type === 'poll_start' || data.type === 'poll_final_results')) {
      return;
  }

  if (data.type === 'ai_student_chat') {
      const studentName = data.from;
      chatMessages.value.push({
          user: studentName,
          content: data.message,
          color: getUserColor(studentName)
      });
      scrollToChatBottom();
      return;
  }
  
  switch (data.type) {
    case 'poll_start':
      currentPoll.value = data.payload;
      pollSubmitted.value = false;
      showFinalResults.value = false;
      Object.keys(pollResults).forEach(key => delete pollResults[key]);
      break;
    case 'poll_answer':
      if (userRole.value === 'publisher') {
        const answerIndex = data.payload.answer;
        pollResults[answerIndex] = (pollResults[answerIndex] || 0) + 1;
      }
      break;
    case 'poll_final_results':
      finalResultsData.value = data.payload;
      showFinalResults.value = true;
      currentPoll.value = null;
      break;
  }
};

const chartOption = computed(() => {
    if (!finalResultsData.value) return {};
    
    const { question, options, votes } = finalResultsData.value;
    const totalChartVotes = votes.reduce((a, b) => a + b, 0);

    return {
        title: {
            text: question,
            subtext: `总参与人数: ${totalChartVotes}`,
            left: 'center',
            top: '5%',
            textStyle: { fontSize: 20, color: '#333', fontWeight: 'bold' },
            subtextStyle: { fontSize: 14, color: '#888' }
        },
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: '{b}: {c} 票' },
        grid: { left: '3%', right: '12%', bottom: '3%', containLabel: true },
        xAxis: { type: 'value', boundaryGap: [0, 0.1], axisLabel: { show: false }, splitLine: { show: false } },
        yAxis: {
            type: 'category',
            data: options,
            axisTick: { show: false },
            axisLine: { show: false },
            axisLabel: {
                color: '#555',
                fontSize: 14,
                fontWeight: 'bold',
                formatter: (value) => value.length > 15 ? value.substring(0, 15) + '...' : value
            }
        },
        series: [{
            name: '票数',
            type: 'bar',
            data: votes,
            barWidth: '60%',
            itemStyle: {
                borderRadius: [0, 8, 8, 0],
                color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                    { offset: 0, color: '#83bff6' },
                    { offset: 0.5, color: '#188df0' },
                    { offset: 1, color: '#5a6fc0' }
                ]),
                shadowColor: 'rgba(0, 0, 0, 0.2)',
                shadowBlur: 5,
                shadowOffsetY: 2,
            },
            label: {
                show: true,
                position: 'right',
                color: '#333',
                fontSize: 14,
                formatter: (params) => {
                    const percentage = totalChartVotes === 0 ? 0 : ((params.value / totalChartVotes) * 100).toFixed(1);
                    return `${params.value} 票 (${percentage}%)`;
                }
            },
            emphasis: { focus: 'series' },
            animationDuration: 800,
            animationEasing: 'cubicOut'
        }]
    };
});

const layoutMode = computed(() => {
  if (isSharingScreen.value) return 'layout-screenshare';
  if (videoTracks.value.length < 2) return 'layout-speaker';
  return 'layout-grid';
});

const handleRecording = async () => {
  isRecordingLoading.value = true;
  if (!isRecording.value) {
    try {
      const result = await livekitService.startRecording(roomName.value);
      egressId.value = result.egressId;
      isRecording.value = true;
      ElMessage.success('录制已开始');
    } catch (error) {
      ElMessage.error(error.message || '开始录制失败');
    } finally {
      isRecordingLoading.value = false;
    }
  } else {
    try {
      if (!egressId.value) throw new Error('无法找到录制ID');
      await livekitService.stopRecording(egressId.value);
      isRecording.value = false;
      egressId.value = null;
      ElMessage.info('录制已停止。');
    } catch (error) {
      ElMessage.error(error.message || '停止录制失败');
    } finally {
      isRecordingLoading.value = false;
    }
  }
};

const disconnect = async () => {
  if (isRecording.value && egressId.value) {
    try {
      await livekitService.stopRecording(egressId.value);
    } catch (e) { /* silent */ }
  }
  if (isSimulating.value) {
    await simulationService.stopSimulation();
    isSimulating.value = false;
  }
  if (room.value) await room.value.disconnect();
};

const attachTrack = (track) => {
  if (track.kind !== Track.Kind.Video || !videoContainerRef.value) return;
  const elementWrapper = document.createElement('div');
  elementWrapper.classList.add('participant-video');
  elementWrapper.setAttribute('data-track-sid', track.sid);
  if (track.source === Track.Source.Camera) elementWrapper.classList.add('camera-track');
  else if (track.source === Track.Source.ScreenShare) elementWrapper.classList.add('screenshare-track');
  const element = track.attach();
  elementWrapper.appendChild(element);
  videoContainerRef.value.appendChild(elementWrapper);
};

const detachTrack = (track) => {
    if (track.kind !== Track.Kind.Video) return;
    const elements = document.querySelectorAll(`[data-track-sid="${track.sid}"]`);
    elements.forEach(el => el.remove());
}

const handleTrackSubscribed = (track) => {
  attachTrack(track);
  if (track.kind === Track.Kind.Video) {
    videoTracks.value.push(track.sid);
    if (track.source === Track.Source.ScreenShare) isSharingScreen.value = true;
  }
};

const handleTrackUnsubscribed = (track) => {
  detachTrack(track);
  if (track.kind === Track.Kind.Video) {
    videoTracks.value = videoTracks.value.filter(sid => sid !== track.sid);
    if (track.source === Track.Source.ScreenShare) isSharingScreen.value = false;
  }
};

const handleLocalTrackPublished = (publication) => publication.track && handleTrackSubscribed(publication.track);
const handleLocalTrackUnpublished = (publication) => publication.track && handleTrackUnsubscribed(publication.track);

const connectToRoom = async () => {
  try {
    if (!authStore.user?.username) {
        ElMessage.error('无法获取用户信息，请重新登录');
        isLoading.value = false;
        return;
    }
    const token = await livekitService.getJoinToken(roomName.value, authStore.user.username, userRole.value);
    room.value = new Room({ serverUrl: livekitUrl, videoCaptureDefaults: { resolution: '720p' } });
    room.value
      .on(RoomEvent.Connected, () => { isConnected.value = true; isLoading.value = false; })
      .on(RoomEvent.Disconnected, () => { isConnected.value = false; isSharingScreen.value = false; videoTracks.value = []; if (videoContainerRef.value) videoContainerRef.value.innerHTML = ''; currentPoll.value = null; showFinalResults.value = false; })
      .on(RoomEvent.TrackSubscribed, handleTrackSubscribed)
      .on(RoomEvent.TrackUnsubscribed, handleTrackUnsubscribed)
      .on(RoomEvent.LocalTrackPublished, handleLocalTrackPublished)
      .on(RoomEvent.LocalTrackUnpublished, handleLocalTrackUnpublished)
      .on(RoomEvent.DataReceived, handleDataReceived);

    await room.value.connect(livekitUrl, token);
    if (userRole.value === 'publisher') await room.value.localParticipant.enableCameraAndMicrophone();
  } catch (error) {
    ElMessage.error(error.message || '进入直播间失败');
    isLoading.value = false;
  }
};

const toggleScreenShare = async () => {
  if (!room.value || !isConnected.value) return;
  try {
    const isCurrentlySharing = room.value.localParticipant.isScreenShareEnabled;
    await room.value.localParticipant.setScreenShareEnabled(!isCurrentlySharing, { audio: true });
  } catch (error) {
    console.error('切换屏幕共享失败:', error);
    ElMessage.error('无法开启屏幕共享，请检查浏览器权限或设置');
  }
};

onMounted(connectToRoom);

onUnmounted(async () => {
    speechRecognitionService.stop();
    await disconnect();
});
</script>

<style scoped>
.main-content-wrapper {
    width: 100%;
}
.live-layout {
    display: flex;
    gap: 16px;
    height: 68vh;
}
.video-container { 
    flex-grow: 1;
    height: 100%;
    background-color: #2c3e50; 
    border-radius: 8px; 
    transition: all 0.3s ease; 
    overflow: hidden;
    position: relative;
}
.sidebar-panel {
    width: 320px;
    flex-shrink: 0;
    height: 100%;
}
.chat-card {
    height: 100%;
    display: flex;
    flex-direction: column;
}
.chat-card :deep(.el-card__body) {
    flex-grow: 1;
    padding: 10px;
    overflow-y: hidden;
}
.chat-header {
    font-weight: bold;
}
.chat-messages {
    height: 100%;
    overflow-y: auto;
    padding-right: 5px; /* for scrollbar */
}
.chat-message {
    margin-bottom: 12px;
    line-height: 1.5;
    font-size: 14px;
    word-break: break-all;
}
.chat-user {
    font-weight: bold;
    margin-right: 8px;
}
.final-results-panel {
    margin-top: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
.final-results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}
.final-results-header span {
    font-weight: bold;
}
.chart-container {
    height: 350px;
    padding: 20px;
}
.chart {
    height: 100%;
    width: 100%;
}

.card-header { display: flex; align-items: center; font-weight: bold; }
:deep(.participant-video) { width: 100%; height: 100%; background-color: #222; }
:deep(video), :deep(audio) { width: 100%; height: 100%; }
.layout-speaker { display: flex; justify-content: center; align-items: center; }
.layout-speaker :deep(.participant-video) { width: 100%; height: 100%; }
.layout-speaker :deep(video) { object-fit: contain; }
.layout-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem; padding: 1rem; }
.layout-grid :deep(.participant-video) { border-radius: 8px; overflow: hidden; }
.layout-grid :deep(video) { object-fit: cover; }
.layout-screenshare { position: relative; display: flex; justify-content: center; align-items: center; }
.layout-screenshare :deep(.participant-video) { display: none; }
.layout-screenshare :deep(.screenshare-track) { display: block; width: 100%; height: 100%; }
.layout-screenshare :deep(.screenshare-track video) { object-fit: contain; }
.layout-screenshare :deep(.camera-track) { display: block; position: absolute; width: 22%; min-width: 180px; max-width: 280px; aspect-ratio: 16 / 9; right: 20px; bottom: 20px; z-index: 10; border: 2px solid rgba(255, 255, 255, 0.6); border-radius: 8px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.3); transition: all 0.3s ease; }
.layout-screenshare :deep(.camera-track:hover) { transform: scale(1.05); border-color: #fff; }
.footer-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}
.control-group-left, .control-group-center, .control-group-right {
    display: flex;
    gap: 10px;
}
.btn-text {
    margin-left: 5px;
}
@media (max-width: 850px) {
    .btn-text {
        display: none;
    }
}
.poll-overlay, .poll-results-overlay {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 100;
  width: 320px;
}
.poll-card {
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(5px);
}
.poll-card h4 {
  text-align: center;
  margin-bottom: 5px;
  font-size: 14px;
}
.poll-question {
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
}
.poll-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.poll-options .el-button {
  width: 100%;
  margin: 0;
}
.poll-feedback {
  margin-top: 10px;
  color: #67c23a;
  text-align: center;
  font-size: 14px;
}
.poll-result-item {
  margin-top: 10px;
}
.poll-result-item span {
  font-size: 14px;
  color: #606266;
}
</style>